import ApiV1WxContactSave_post from "@/api/ApiV1WxContactSave_post";
import type { IRawContact } from "@/chatlog_types/IRawContact";
import { TaskType } from "../tasks/TaskType";
import { contacts_forage } from "./ContactsMgr";
import { ITask } from "../tasks";

export function create_contact_commit_job(raw: IRawContact): ITask<TaskType.Contact, IRawContact> {
  const phone_in_remark = raw.remark?.match(/1[3-9]\d{9}/)?.[0] ?? void 0;
  const job = {
    id: `contact_${raw.account}_${raw.userName}`,
    title: `提交${raw.account}的联系人`,
    desc: `用户名: ${raw.userName} 昵称: ${raw.nickName}`,
    data: raw,
    type: TaskType.Contact as const,
    run: async () => {
      const key = `contact_item##${raw.account}##${raw.userName}`;
      /*
      step0. 查看"本地数据"是否"不存在或有差异"
      step1. 提交数据至服务端
      step2. 完成提交，记录在"本地数据"
      */
      return ApiV1WxContactSave_post.call(raw).then(() => {
        raw.phone = phone_in_remark;
        return contacts_forage.setItem(key, raw);
      });
    }
  };

  return job;
}
